//
//  UIImageView+WebCache.m
//  SDWebImage
//
//  Created by 刘建镇 on 14-12-23.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "UIImageView+WebCache.h"
#import "ToolsImageCache.h"

@implementation UIImageView (WebCache)

- (void)setImageWithUrl:(NSString *)urlStr placeHolder:(NSString *)place
{
    //获取本地图片文件
    UIImage *aImage = [self imageWithName:[self fileName:urlStr]];
    if (aImage) {
        self.image = aImage;
    }else
    {
        NSString *str = [urlStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        //下面这个多余, 应该在存储的时候 才进行变换地址, 以便于保存文件路径, 所以只要写在访问路径的时候进行修改url变成文件名即可.
//        NSString *fileN = [str stringByReplacingOccurrencesOfString:@"/" withString:@""];
        NSURL *url = [NSURL URLWithString:str];
        
        [self downImageWithUrl:url fileName:str];
    }
}

//自定义方法: 根据图片数据生成图片
- (UIImage *)imageWithName:(NSData *)data
{
    self.image = [UIImage imageWithData:data];
    return self.image;
}

//自定义方法: 获得图片数据
- (NSData *)fileName:(NSString *)fileName
{
    NSData *data = [ToolsImageCache dataWithFileName:fileName];
    return data;
}

//异步下载图片并缓存本地
- (void)downImageWithUrl:(NSURL *)url fileName:(NSString *)fileName
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage *image = [UIImage imageWithData:data];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.image = image;
        [ToolsImageCache saveFile:data fileName:fileName];
        });
    });
}
@end
